package com.weishi.project.mcs8.controller;

import com.weishi.common.enums.RedisConstants;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.redis.RedisCache;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.vo.TrainingAchievementMaxVo;
import com.weishi.project.mcs8.Mcs8Cilent;
import com.weishi.project.mcs8.vo.DeviceVo;
import com.weishi.project.speedometer.vo.DevInfo;
import com.weishi.project.training.domain.ShipSpeedRecordLog;
import com.weishi.project.training.service.IShipSpeedRecordLogService;
import com.weishi.project.training.service.ISportsmanService;
import com.weishi.project.training.service.ITrainingAchievementService;
import com.weishi.project.training.service.ITrainingGroupChannelService;
import com.weishi.tcp.tcpserver.TCPServer;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.logging.Logger;

@RestController
@CrossOrigin("*")//解决移动端跨域
@RequestMapping("/app/mcs8")
public class Mcs8ApiController {

    private Logger logger = Logger.getLogger("mcs8Service");

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISportsmanService sportsmanService;

    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    @Autowired
    private IShipSpeedRecordLogService shipSpeedRecordLogService;


    @ApiOperation(value = "获取设备列表")
    @GetMapping("/getDevList")
    public AjaxResult getDevList(@RequestParam Map<String, Object> objectMap) {
        Mcs8Cilent mcs8Cilent = Mcs8Cilent.getInstant();
        List<DeviceVo> list = mcs8Cilent.getDeviceList("21");
        if (objectMap.get("status") != null) {
            List<DeviceVo> retList = new ArrayList<>();
            int status = Integer.parseInt(objectMap.get("status").toString());
            for (DeviceVo deviceVo : list) {
                if (deviceVo.getStatus() == status) {
                    retList.add(deviceVo);
                }
            }
            list = retList;
        }
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "获取历史视频")
    @GetMapping("/getRecordFile")
    public AjaxResult getRecordFile(@RequestParam Map<String, Object> objectMap) {
        Date date = new Date();
        List<String> list = null;
        try {
            String deviceId = objectMap.get("deviceId") == null ? null : objectMap.get("deviceId").toString();
            String stime = objectMap.get("stime") == null ? DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getSpecifiedDayAfter(date, -30)) : objectMap.get("etime").toString();
            String etime = objectMap.get("etime") == null ? DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date) : objectMap.get("stime").toString();
            int page = objectMap.get("page") == null ? 0 : Integer.parseInt(objectMap.get("page").toString());
            int pageSize = objectMap.get("pageSize") == null ? 5 : Integer.parseInt(objectMap.get("pageSize").toString());
            Mcs8Cilent mcs8Cilent = Mcs8Cilent.getInstant();
            list = mcs8Cilent.getHistoryFileList(deviceId, stime, etime, page, pageSize);
        } catch (NumberFormatException e) {
            list = new ArrayList<>();
            e.printStackTrace();
        }
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "发送信息到设备")
    @GetMapping("/sendMsg")
    public AjaxResult sendMsg(@RequestParam Map<String, Object> objectMap) {
        String message = objectMap.get("message").toString();
        TCPServer tcpServer = TCPServer.getInstance();
        tcpServer.TCPServerSendStrALL(message);
        return AjaxResult.success(message);
    }


    @ApiOperation("PC 端 -- 通过devId获取数据")
    @RequestMapping(value = "/getDevInfo", method = RequestMethod.POST)
    public AjaxResult getDevInfo(@RequestBody com.alibaba.fastjson.JSONObject jsonObject) {
        DevInfo devInfo = redisCache.getCacheObject(RedisConstants.Dev_Info_Prefix + jsonObject.get("devId").toString());
        List<Map<String, Object>> retList = new ArrayList<>();
        Map<String, Object> retMap = new HashMap<>();

        if (StringUtils.isNull(devInfo) || devInfo.getStatus() == 0 || StringUtils.isNull(devInfo.getStartTime())) {
            return AjaxResult.success();
        } else {
            Map<String, Object> distanceMap = new HashMap<>();
            distanceMap.put("距离", devInfo.getDistance());
            retList.add(distanceMap);

            Map<String, Object> speedMap = new HashMap<>();
            speedMap.put("速度", devInfo.getSpeed());
            retList.add(speedMap);

            Map<String, Object> propellerFrequencyMap = new HashMap<>();
            propellerFrequencyMap.put("桨频", devInfo.getPropellerFrequency());
            retList.add(propellerFrequencyMap);

            ShipSpeedRecordLog params = new ShipSpeedRecordLog();
            params.setChannelId(devInfo.getChannelId());
            List<ShipSpeedRecordLog> list = shipSpeedRecordLogService.selectShipSpeedRecordLogList(params);
            if(StringUtils.isNotEmpty(list)) retMap.put("realData", getTableData(list, devInfo.getStartTime()));


            if (devInfo.getChannelId() != 0) {
                List<TrainingAchievementMaxVo> vos = trainingAchievementService.selectTrainingAchievementListByChannelId(devInfo.getChannelId());
                for (TrainingAchievementMaxVo vo : vos) {
                    int heartCount = sportsmanService.getHeartCount(vo.getSportsmanId());
                    Map<String, Object> heartCountMap = new HashMap<>();
                    heartCountMap.put(vo.getName(), heartCount);
                    retList.add(heartCountMap);
                }
            }

            retMap.put("map", retList);
            return AjaxResult.success(retMap);
        }
    }

    private Map<String, Object> getTableData(List<ShipSpeedRecordLog> list, String startTime) {
        Map<String, Object> ret = new HashMap<>();
        List<String> x = new ArrayList<>();
        List<Double> ySpeed = new ArrayList<>();
        List<Integer> yPropellerFrequency = new ArrayList<>();
        List<Double> yDistance = new ArrayList<>();
        for (ShipSpeedRecordLog shipSpeedRecordLog : list) {
            x.add(getRealTime(startTime,Long.parseLong(shipSpeedRecordLog.getTimp())));
            ySpeed.add(shipSpeedRecordLog.getSpeed());
            yPropellerFrequency.add(shipSpeedRecordLog.getPropellerFrequency());
            yDistance.add(shipSpeedRecordLog.getDistance());
        }

        ret.put("x", x);
        ret.put("ySpeed", ySpeed);
        ret.put("yPropellerFrequency", yPropellerFrequency);
        ret.put("yDistance", yDistance);
        return ret;
    }

    private String getRealTime(String startTime, long end) {
        long start = DateUtils.parseDate(startTime).getTime();
        return DateUtils.getStringTime(end - start);

    }
}
